package com.example.reading.controller;

import com.example.reading.entity.Book;
import com.example.reading.entity.Reader;
import com.example.reading.properties.AmazonProperties;
import com.example.reading.repository.ReadingListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping("/readingList")
public class ReadingListController {

    @Autowired
    private ReadingListRepository repository;


    @Autowired
    private AmazonProperties amazonProperties;

    @RequestMapping(value = "/{reader}",method = RequestMethod.GET)
    public String readersBooks(@PathVariable("reader") String reader, Model model){

        List<Book> readingList = repository.findByReader(reader);

        if(readingList != null){
            model.addAttribute("books",readingList);
            model.addAttribute("reader",reader);
            model.addAttribute("amazonId",amazonProperties.getAssociateId()
            );
        }
        return "readingList";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String addTOReadingList(@PathVariable("reader")String reader,Book book){
        book.setReader(reader);
        repository.save(book);
        return "redirect:/readingList/{reader}";
    }

}
